package in.abip.chisame;

import java.util.List;
import in.abip.chisame.model.ISwitch;
import in.abip.chisame.model.Light;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

/**
 * Light activity.
 * 
 * @author Julot.
 * @since Thursday, January 26th, 2011.
 */
public class LightListActivity extends NetworkActivity {
	private Adapter _adapter = null;

	/**
	 * Adapter for light list view.
	 * 
	 * @author Julot.
	 * @since Thursday, January 27, 2011.
	 */
	private class Adapter extends ListAdapter {
		public Adapter(Context context, int viewResourceId, List<Object> objects) {
			super(context, viewResourceId, objects);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			Light item = (Light) _objects.get(position);

			Button on = (Button) view.findViewById(R.id.on);
			on.setTag(item);
			on.setOnClickListener(_onClickListener);
			
			Button off = (Button) view.findViewById(R.id.off);
			off.setTag(item);
			off.setOnClickListener(_offClickListener);
			
			SeekBar seekBar = (SeekBar) view.findViewById(R.id.seek);
			seekBar.setTag(item);
			if (item.hasRange) {
				seekBar.setOnSeekBarChangeListener(_changeListener);
				seekBar.setProgress(item.getValue());
				seekBar.setVisibility(SeekBar.VISIBLE);
			} else {
				seekBar.setVisibility(SeekBar.INVISIBLE);
			}
			// ImageView image = (ImageView) view.findViewById(R.id.image);
			// image.setOnClickListener(_clickListener);
			// registerForContextMenu(image);
			TextView text = (TextView) view.findViewById(R.id.text);
			// text.setOnClickListener(_clickListener);
			// registerForContextMenu(text);
			text = (TextView) view.findViewById(R.id.value);
			text.setText(item.getValueName());
			return view;
		}
	}

	private OnClickListener _onClickListener = new OnClickListener() {
		public void onClick(View view) {
			Light light = (Light) view.getTag();
			inputs.add(light.getRunCmd());
			light.setValue(100);
			send(light.getRunCmd());
		}
	};

	private OnClickListener _offClickListener = new OnClickListener() {
		public void onClick(View view) {
			Light light = (Light) view.getTag();
			inputs.add(light.getRunCmd());
			light.setValue(0);
			send(light.getRunCmd());
		}
	};

	/**
	 * Listener for image and text click.
	 */
	// private OnClickListener _clickListener = new OnClickListener() {
	// public void onClick(View view) {
	// Light light = (Light) view.getTag();
	// inputs.add(light.getRunCmd());
	// light.toggle();
	// send(light.getRunCmd());
	// }
	// };

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		Light light = (Light) v.getTag();
		menu.setHeaderTitle("Light");
		menu.add(0, light._id.intValue(), 0, R.string.edit);
		menu.add(0, light._id.intValue(), 0, R.string.delete);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		Integer pk = item.getItemId();
		Light light = (Light) Light.model().findByPk(pk);
		Toast.makeText(this, item.getTitle() + " -> " + light.name,
				Toast.LENGTH_SHORT).show();
		return true;
	}

	/**
	 * Listener for seek bar.
	 */
	private OnSeekBarChangeListener _changeListener = new OnSeekBarChangeListener() {
		public void onStopTrackingTouch(SeekBar seekBar) {
			Light light = (Light) seekBar.getTag();
			light.setValue(seekBar.getProgress());
			send(light.getRunCmd());
		}

		public void onStartTrackingTouch(SeekBar seekBar) {
			Light light = (Light) seekBar.getTag();
			inputs.add(light.getRunCmd());
		}

		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			View parent = (View) seekBar.getParent();
			ISwitch model = (ISwitch) seekBar.getTag();
			TextView text = (TextView) parent.findViewById(R.id.value);
			text.setText(model.getValueName(seekBar.getProgress()));

			if (fromUser) {
				Light light = (Light) seekBar.getTag();
				light.setValue(progress);
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_activity);
	}

	/** Populate list view. */
	@Override
	protected void populate() {
		_adapter = new Adapter(this, R.layout.list_item_seekbar, loadLights());
		ListView view = (ListView) findViewById(R.id.list);
		view.setAdapter(_adapter);
	}

	/**
	 * Load lights.
	 * 
	 * @return {@link List}
	 */
	private List<Object> loadLights() {
		Bundle bundle = getIntent().getExtras();
		List<Object> lights = null;
		if (bundle != null) {
			lights = Light.model().findAll(
					"roomId = " + bundle.getInt("roomId"));
		} else
			lights = Light.model().findAll();
		return lights;
	}

	/**
	 * Refresh list with current status from server.
	 */
	protected void refresh() {
		String command;
		for (Object item : _adapter.getItems()) {
			Light model = (Light) item;
			command = model.getAskCmd();
			udpOutputs.add(command);
			tcpOutputs.add(command);
		}
		startSend();
	}

	protected void updateUi() {
		String input = null;
		int host;
		int channel;
		int value;
		List<Object> lights;
		Light light;

		lights = _adapter.getItems();
		while ((input = inputs.poll()) != null) {
			Log.d("LightListActivity.updateUi", input);
			host = Integer.parseInt(input.substring(0, 2));
			channel = Integer.parseInt(input.substring(2, 4));
			value = Integer.parseInt(input.substring(4, 7));
			int i = 0;
			while (i < lights.size()) {
				light = (Light) lights.get(i);
				if (light.host == host && light.channel == channel) {
					light.setValue(value);
					break;
				}
				i++;
			}
		}
		_adapter.notifyDataSetChanged();
	};

}
